//
//  ST_ShortcutRechargeController.swift
//  btvideo
//
//  Created by Jason on 2021/9/2.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
//import Rswift
import RxCocoa
import RxSwift
import RxDataSources
import KeychainAccess
import SwiftyAttributes
import SwiftyUserDefaults

class ST_ShortcutRechargeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let fateBackgroundImageViewHeight = ScreenWidth/375.0*91
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(16)
            
            if iPhoneXSeries{
                make.height.equalTo(fateBackgroundImageViewHeight+346+16+35)
            }else{
                make.height.equalTo(fateBackgroundImageViewHeight+346+16-34+10+35)
            }
        }
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.top.right.left.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        root_view.addSubview(fate_background_image_view)
        fate_background_image_view.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(fateBackgroundImageViewHeight)
        }
        
        
        view.addSubview(top_fate_image_view)
        top_fate_image_view.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-9)
            make.bottom.equalTo(fate_background_image_view)
        }
        
        view.addSubview(fate_gradient_image_view)
        fate_gradient_image_view.snp.makeConstraints { make in
            make.bottom.equalTo(top_fate_image_view)
            make.left.right.equalToSuperview()
            make.height.equalTo(29)
        }
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(25)
            make.top.equalTo(fate_background_image_view.snp.bottom).offset(9)
        }
        
        
        
        
        root_view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.height.equalTo(60*3+6*2)
        }
        
        root_view.addSubview(inquiry_image_view)
        inquiry_image_view.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-18)
            make.centerY.equalTo(titleLabel)
        }
        
        root_view.addSubview(inquiry_image_btn)
        inquiry_image_btn.snp.makeConstraints { make in
            make.edges.equalTo(inquiry_image_view)
        }
//        50
        
        
        root_view.addSubview(agreement_btn)
        agreement_btn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(12)
            make.height.equalTo(20)
        }
        
        root_view.addSubview(coin_value_label)
        coin_value_label.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.left.equalToSuperview().offset(20)
            if iPhoneXSeries{
                make.bottom.equalToSuperview().offset(-48-16)
            }else{
                make.bottom.equalToSuperview().offset(-48-16+34-10)
            }
        }
        
        
        root_view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { make in
            make.centerY.equalTo(coin_value_label)
            make.height.equalTo(44)
            make.width.equalTo(118)
            make.right.equalToSuperview().offset(-20)
        }
        
        
        setCoinValue()
        
        
        request_data()
    }
    
    fileprivate func request_data(){
        
        
        
        let datasource = RxCollectionViewSectionedReloadDataSource<SectionModel<String,ST_TIANRechargeCellTypeItem>>.init { dataSource, collectionView, indexPath, model in

            switch model {
            case .normal(let value):
                
                let cell = collectionView.dequeueReusableCell(withClass: ST_TIANRechargeCell.self, for: indexPath)

                cell.model = value
                
                return cell
                
            case .other:
                
                let cell = collectionView.dequeueReusableCell(withClass: ST_TIANRechargeOtherCell.self, for: indexPath)

                return cell
            }
            
            
        }
        
        dataObservable.bind(to: self.collectionView.rx.items(dataSource: datasource)).disposed(by: self.disposeBag)
        
        collectionView.rx.itemSelected.subscribe(onNext: { indexPath in
            
            guard let curr = self.data_array[safe:indexPath.row] else {
                return
            }
            
            switch curr{
                
            case .normal(let value):
                
                if let last = self.last_selected_index_path{
                    self.data_array[safe:last.row]?.setSelected(value: false)
                }
//                self.data_array[safe:indexPath.row]?.isSelected = true
                value.isSelected = true
                
                self.dataObservable.accept([SectionModel<String,ST_TIANRechargeCellTypeItem>(model: "", items: self.data_array)])
                
                self.last_selected_index_path = indexPath
                
            case .other(let value):
                
                GlobalPresent(toController: ST_DesignOpenWayTipsController(way: value))
                
            }
            
            
        }).disposed(by: disposeBag)
        
        JVrequest(PH.getAppleCoinPriceApi, success: { (json) in

            let data = json["data"]
            let list = data["list"].arrayValue.map({ ST_TIANRechargeCellModel.deserialize(from: $0.rawString() ) }).compactMap({ $0 })
            
            var i = 0
            for index in 0 ..< list.count {
                let m = list[index]
                if m.original_price.int == 98 {
                    list[index].isSelected = true
                    i = index
                }
            }
//            list.first?.isSelected = true
            
            
            
            if list[safe: i] != nil{
                self.last_selected_index_path = IndexPath(row: i, section: 0)
            }
            
            self.data_array = list.map{ ST_TIANRechargeCellTypeItem.normal(value: $0) }
            
            if let url0 = data["link"]["preview_url"].url,let url1 = data["link"]["open_url"].url{
            
                let linkData = data["link"]
                
                let way = ST_DesignOpenWayStruct(title: linkData["title"].stringValue, preUrl: url0, judge_u_r_l: url1)
                
                self.data_array.append(ST_TIANRechargeCellTypeItem.other(item: way))
                
            }
            
            
            self.dataObservable.accept([SectionModel<String,ST_TIANRechargeCellTypeItem>(model: "", items: self.data_array)])
            
            
            self.re_set_view()
        }) { (code, err) in
            
            
            self.toast(text: err)
        }
        
        
    }
    
    private func setCoinValue(){
        
        var str = "余额："
        
        str += (ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sweet_coin ?? 0).int.string
        
        coin_value_label.setTitle(str.withAttributes(coin_value_attributes), for: .normal)
        
    }
    
    
    
    func re_set_view() {
        let count = data_array.count
        let row = count / 3 + 1
        let collectionviewHeight = (70 * row) + (10 * (row - 1))
        
        root_view.snp.updateConstraints { make in
            make.height.equalTo(225 + BTSafeAreaBottom.int + 16 + collectionviewHeight + 35)
        }
        
        collectionView.snp.updateConstraints { make in
            make.height.equalTo(collectionviewHeight)
        }
        
        self.view.layoutIfNeeded()
    }
    
//    MARK: - properties
    fileprivate lazy var close_view:UIControl = {
        let control = UIControl()
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = .white
        control.cornerRadius = 16
        return control
    }()
    
    fileprivate lazy var top_fate_image_view:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("shortcut_recharge_fate_icon"))
        return v
    }()
    
    fileprivate lazy var fate_background_image_view:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("shortcut_recharge_fate_background"))
        return v
    }()
    
    fileprivate lazy var fate_gradient_image_view:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("shortcut_recharge_gradient"))
        return v
    }()
    
    
    
    
    fileprivate lazy var titleLabel:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        l.font = .systemFont(ofSize: 16, weight: .semibold)
        l.text = "充值甜心币"
        return l
    }()
    
    fileprivate lazy var inquiry_image_view:ST_TianButton = {
        let v = ST_TianButton(style: .title_left_image_right(titleLeft: 0, imageSize: CGSize(width: 16, height: 16), layout: ST_TianButtonLayoutModel.inside_auto_resize(relevantOffset: 4, lastControlEdgeValue: 0)))
        v.setImage(ST_ImageUtils.imageName("why_green_icon"), for: .normal)
        v.setTitle("充值帮助".withAttributes([.font(.systemFont(ofSize: 13, weight: .regular)),.textColor(UIColor(hexString: "#999999")!)]), for: .normal)
        v.isUserInteractionEnabled = false
        return v
    }()
    
    fileprivate lazy var inquiry_image_btn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.addTarget(self, action: #selector(inquiry_handle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    fileprivate lazy var agreement_btn:UIButton = {
        
        let control = UIButton(type: .custom)
        
        let str = "充值代表阅读并同意".withAttributes([.font(.systemFont(ofSize: 14, weight: .regular)),.textColor(UIColor(hex: 0x8D8D8D)!)])
        
        str.append("《用户充值协议》".withAttributes([.font(.systemFont(ofSize: 14, weight: .regular)),.textColor(UIColor(hex: 0x3598FF)!)]))
                   
       control.setAttributedTitle(str, for: .normal)

        control.addTarget(self, action: #selector(jump_to_recharge_protocol_page), for: .touchUpInside)
        return control
    }()
    
    
    @objc private func jump_to_recharge_protocol_page(){
        
        let vc = ST_BTWebViewController()
        
        vc.overCurrentContext = true
        
        vc.urlStr = PH.userRechargeProtocolURL
        
        vc.titleStr = "充值协议"
        
        GlobalPresent(toController: vc)
        
    }
    
    private lazy var coin_value_attributes:[Attribute] = [.font(.systemFont(ofSize: 14, weight: .regular)),.textColor(UIColor(hex: 0x333333)!)]

    fileprivate lazy var coin_value_label:ST_TianButton = {
        let l = ST_TianButton(style: .image_left_title_right(imageLeft: 0, imageSize: CGSize(width: 20, height: 20), layout: ST_TianButtonLayoutModel.inside_auto_resize(relevantOffset: 8, lastControlEdgeValue: 0)))
        l.setImage(ST_ImageUtils.imageName("shortcut_recharge_coin_icon"), for: .normal)
        return l
    }()
    
    fileprivate lazy var confirm_btn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = #colorLiteral(red: 0.9960784314, green: 0.7607843137, blue: 0.02745098039, alpha: 1)
        btn.setTitle("充值", for: .normal)
        btn.cornerRadius = 20
        //btn.semanticContentAttribute = .forceRightToLeft
        btn.addTarget(self, action: #selector(confirm_handle), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.scrollDirection = .vertical
        controlLayout.minimumLineSpacing = 10
        controlLayout.minimumInteritemSpacing = 10
        
        controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        let w = (ScreenWidth - 20*2 - 10*2)/3.0
        controlLayout.itemSize = CGSize.init(width: w, height: 70)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
     
        control.register(cellWithClass: ST_TIANRechargeCell.self)
        control.register(cellWithClass: ST_TIANRechargeOtherCell.self)
        
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = UIColor.white
        //        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        control.clipsToBounds = false
        
        return control
    }()
    
    var disposeBag = DisposeBag()
    
    fileprivate var data_array = [ST_TIANRechargeCellTypeItem]()
    
    let dataObservable = BehaviorRelay(value: [SectionModel<String,ST_TIANRechargeCellTypeItem>(model: "", items: [])])
    
    fileprivate var last_selected_index_path:IndexPath?
    
//    {
//        didSet{
//
//            guard let last = last_selected_index_path, let item = self.data_array[safe: last.row] else { return  }
//
////            let str = "立即充值" + item.original_price.int.string + "元"
////
////            confirm_btn.setTitle(str, for: .normal)
//
//        }
//    }
}

extension ST_ShortcutRechargeController{
    
    @objc fileprivate func inquiry_handle(){
    
        if Defaults[.isPanda]{
            
            
            guard let url = URL(string: PH.helpPayHtml.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) else { return  }
            
            let vc = ST_RegistStepHelperController()
            
            vc.url = url
            
            vc.hiddenfeedback = true
            
            GlobalPresent(toController: vc)
            
        }else{
            
            GlobalPresent(toController: UINavigationController.create_hiding_bar_navigation_controller(rootViewController: ST_DesignDAController()))
            
        }
    
    }
    
    
    @objc fileprivate func close_handle(){
        
        goback_previous_controller()
        
    }
    
    @objc fileprivate func confirm_handle(){
        
        guard let curr = last_selected_index_path, let item_model = data_array[safe: curr.row] else { return  }
        
        switch item_model {
        case .normal(let itemValue):
            
            
            let str = itemValue.descr+itemValue.original_price.int.string+"元"+itemValue.ename
            
            ST_BTGlobalDataCenter.shared.payMenuPage(paramValue: str)
            
            ST_MaidWayManager.shared.doWay(id: itemValue.id.string, delegate: self)
            
        default:
            break
        }
        
        
    }
}


extension ST_ShortcutRechargeController:ST_TIANPaymentTransactionStateDelegate{
            
     func transaction_succeed(){
         
         setCoinValue()
         
         let vc = BTVerticalAlertViewController.createRechargeSuccessAlert()
         
         vc.confirm_closure = {
             self.goback_previous_controller()
         }
         
         GlobalPresent(toController: vc)
        
     }
    
    
}

enum ST_TIANRechargeCellTypeItem {
    case normal(value:ST_TIANRechargeCellModel)
    case other(item:ST_DesignOpenWayStruct)
    
    func setSelected(value:Bool){
        switch self {
        case .normal(let normalValue):
            normalValue.isSelected = value
        case .other:
            break
        }
    }
}


class ST_TIANRechargeOtherCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(imgView)
        imgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var imgView:UIImageView = {
        let v = UIImageView()
        v.contentMode = .scaleToFill
        v.pin_setImage(from: "http://btstatic-cdn.jingniaoapps.com/w27c20h1646362976".url)
        return v
    }()
    
}



class ST_TIANRechargeCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.clipsToBounds = false
        
        contentView.addSubview(root_view)
        root_view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.addSubview(cornerMarkImageView)
        cornerMarkImageView.snp.makeConstraints { make in
            make.right.top.equalToSuperview()
            make.width.equalTo(34)
            make.height.equalTo(16)
        }
        
        cornerMarkImageView.addSubview(cornerMarkLabel)
        cornerMarkLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        
        
        root_view.addSubview(coin_count_label)
        coin_count_label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.top.equalToSuperview().offset(12)
            make.height.equalTo(26)
        }
        
        root_view.addSubview(coin_name_label)
        coin_name_label.snp.makeConstraints { make in
            make.left.equalTo(coin_count_label.snp.right).offset(2)
            make.top.equalToSuperview().offset(19)
            make.height.equalTo(17)
        }
        
        root_view.addSubview(price_label)
        price_label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-12)
            make.height.equalTo(17)
        }
        
        contentView.addSubview(hot_image_view)
        hot_image_view.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(-12)
            make.size.equalTo(CGSize(width: 42, height: 42))
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//
    fileprivate lazy var cornerMarkImageView:UIImageView = {
        let v = UIImageView(image: ST_ImageUtils.imageName("recharge_corner_mark"))
        v.alpha = 0
        return v
    }()
    
    fileprivate lazy var cornerMarkLabel:UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.font = .systemFont(ofSize: 10, weight: .semibold)
        l.textAlignment = .center
        return l
    }()
    
    
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.backgroundColor = #colorLiteral(red: 0.9960784314, green: 0.7607843137, blue: 0.02745098039, alpha: 0.1)
        control.cornerRadius = 10
        control.borderColor = .clear
        control.borderWidth = 2
        return control
    }()
    
    
    fileprivate lazy var coin_count_label:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        l.font = UIFont.init(name: "DINPro-Black", size: 20)
        return l
    }()
    
    fileprivate lazy var coin_name_label:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        l.text = "甜心币"
        l.font = UIFont.systemFont(ofSize: 12, weight: .semibold)
        return l
    }()
    
    fileprivate lazy var price_label:UILabel = {
        let l = UILabel()
        l.textColor = #colorLiteral(red: 0.3882352941, green: 0.3529411765, blue: 0.3490196078, alpha: 1)
        l.font = UIFont.systemFont(ofSize: 12, weight: .regular)
        return l
    }()
    
    fileprivate lazy var hot_image_view: UIImageView = {
        let i = UIImageView()
        i.image = ST_ImageUtils.imageName("quick_hot")
        return i
    }()
    
    
    var model:ST_TIANRechargeCellModel?{
        didSet{

            guard let m = model else { return  }
            
            coin_count_label.text = m.limited_time.string
            
            price_label.text = m.original_price.int.string + "元"
            
            if m.alternative_descr.count > 0{
                cornerMarkImageView.alpha = 1
                cornerMarkLabel.text = m.alternative_descr
            }else{
                cornerMarkImageView.alpha = 0
            }
            
            if m.isSelected{
                root_view.borderColor = #colorLiteral(red: 0.9960784314, green: 0.7607843137, blue: 0.02745098039, alpha: 1)
            }else{
                root_view.borderColor = .clear
            }
            
            if m.original_price.int == 98 {
                hot_image_view.isHidden = false
            }else {
                hot_image_view.isHidden = true
            }
        }
    }
    
}


class ST_TIANRechargeCellModel: BTMemberGoodsModel {
    var isSelected = false
}
